package com.example.service.impl;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import com.ruoyi.common.core.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.example.domain.GroupMember;
import com.example.mapper.GroupMapper;
import com.example.domain.Group;
import com.example.service.IGroupService;

/**
 * 分组Service业务层处理
 * 
 * @author 何曼伶
 * @date 2024-12-10
 */
@Service
public class GroupServiceImpl implements IGroupService 
{
    @Autowired
    private GroupMapper groupMapper;

    /**
     * 查询分组
     * 
     * @param id 分组主键
     * @return 分组
     */
    @Override
    public Group selectGroupById(Long id)
    {
        return groupMapper.selectGroupById(id);
    }

    /**
     * 查询分组列表
     * 
     * @param group 分组
     * @return 分组
     */
    @Override
    public List<Group> selectGroupList(Group group)
    {
        return groupMapper.selectGroupList(group);
    }

    /**
     * 新增分组
     * 
     * @param group 分组
     * @return 结果
     */
    @Transactional
    @Override
    public int insertGroup(Group group)
    {
        int rows = groupMapper.insertGroup(group);
        insertGroupMember(group);
        return rows;
    }

    /**
     * 修改分组
     * 
     * @param group 分组
     * @return 结果
     */
    @Transactional
    @Override
    public int updateGroup(Group group)
    {
        groupMapper.deleteGroupMemberByGroupId(group.getId());
        insertGroupMember(group);
        return groupMapper.updateGroup(group);
    }

    /**
     * 批量删除分组
     * 
     * @param ids 需要删除的分组主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteGroupByIds(Long[] ids)
    {
        groupMapper.deleteGroupMemberByGroupIds(ids);
        return groupMapper.deleteGroupByIds(ids);
    }

    /**
     * 删除分组信息
     * 
     * @param id 分组主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteGroupById(Long id)
    {
        groupMapper.deleteGroupMemberByGroupId(id);
        return groupMapper.deleteGroupById(id);
    }

    /**
     * 新增分组设置信息
     * 
     * @param group 分组对象
     */
    public void insertGroupMember(Group group)
    {
        List<GroupMember> groupMemberList = group.getGroupMemberList();
        Long id = group.getId();
        if (StringUtils.isNotNull(groupMemberList))
        {
            List<GroupMember> list = new ArrayList<GroupMember>();
            for (GroupMember groupMember : groupMemberList)
            {
                groupMember.setGroupId(id);
                list.add(groupMember);
            }
            if (list.size() > 0)
            {
                groupMapper.batchGroupMember(list);
            }
        }
    }
}
